package com.ilxqx.framework.amqp.schedule;

import com.ilxqx.framework.amqp.constant.RabbitMessageConstants;
import com.ilxqx.framework.amqp.entity.SysMessageLog;
import com.ilxqx.framework.amqp.enumeration.SysMessageLogStatusEnum;
import com.ilxqx.framework.amqp.po.SysRabbitMessage;
import com.ilxqx.framework.amqp.service.MessageSenderService;
import com.ilxqx.framework.amqp.service.SysMessageLogService;
import com.ilxqx.framework.util.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息检测
 * @author venus
 */
@Component
@Slf4j
public class MessageChecking {

    private final SysMessageLogService sysMessageLogService;
    private final MessageSenderService messageSenderService;

    @Autowired
    public MessageChecking(SysMessageLogService sysMessageLogService, MessageSenderService messageSenderService) {
        this.sysMessageLogService = sysMessageLogService;
        this.messageSenderService = messageSenderService;
    }

    /**
     * 检测发送异常的消息
     */
    @Scheduled(initialDelay = 5000, fixedDelay = 2 * 60 * 1000)
    public void check() {
        log.info("系统开始检测发送异常的消息，并尝试重新发送他们");
        List<SysMessageLog> sysMessageLogList = this.sysMessageLogService.getRetryList(RabbitMessageConstants.MAX_RETRY_COUNT, RabbitMessageConstants.NEED_RETRY_STATUSES);
        if (CollectionUtils.isNotEmpty(sysMessageLogList)) {
            // 有需要重试的消息
            sysMessageLogList.forEach(sysMessageLog -> {
                //更新状态信息
                sysMessageLog.setNextRetryTime(LocalDateTime.now().plusMinutes(2 + sysMessageLog.getTryCount()));
                sysMessageLog.setTryCount(sysMessageLog.getTryCount() + 1);
                sysMessageLog.setStatus(SysMessageLogStatusEnum.SENDING);
                // 保存
                this.sysMessageLogService.modify(sysMessageLog);
                Object object = ObjectUtils.deserializeObjectFromString(sysMessageLog.getContent());
                if (object instanceof SysRabbitMessage) {
                    SysRabbitMessage message = (SysRabbitMessage) object;
                    this.messageSenderService.sendMessage(message, sysMessageLog.getMessageId());
                }
            });
        }
        log.info("检测发送异常的消息结束");
    }

}
